package network_programming.np2_nonblocking_communication;

import java.io.*;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

/**
 * 阻塞模式 EchoClient      单线程
 * 同步通信
 *
 * SocketChannel默认采用阻塞模式
 * */
public class EchoClientBlocking {
    private SocketChannel socketChannel;

    public EchoClientBlocking() throws IOException {
        socketChannel = SocketChannel.open();
        InetAddress serverAddress = InetAddress.getLocalHost();
        InetSocketAddress socketAddress = new InetSocketAddress(serverAddress, 9099);
        socketChannel.connect(socketAddress);   // 连接服务器
        System.out.println("成功与服务器建立连接");
    }

    private BufferedReader getReader(Socket socket) throws IOException {
        InputStream socketIn = socket.getInputStream();
        return new BufferedReader(new InputStreamReader(socketIn, StandardCharsets.UTF_8));
    }

    private PrintWriter getWriter(Socket socket) throws IOException {
        OutputStream socketOut = socket.getOutputStream();
        return new PrintWriter(new OutputStreamWriter(socketOut, StandardCharsets.UTF_8), true);
        // 第二参数设为true则表示此流在每次写入数据时自动刷新
    }

    public void talk() {
        try {
            BufferedReader br = getReader(socketChannel.socket());
            PrintWriter pw = getWriter(socketChannel.socket());
            BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in));
            String msg;
            while ((msg = localReader.readLine()) != null) {
                pw.println(msg);
                System.out.println(br.readLine());
                if ("bye".equals(msg))
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socketChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        new EchoClientBlocking().talk();
    }
}
